package com.kfd.mvc;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

@WebServlet(name = "DispatcherServlet", value = "/DispatcherServlet")
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //获得配置文件的名称
        String path = config.getInitParameter("contentConfigLocation");
        //获得配置文件的输入流
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);

        HandlerMapping.load(is);

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户请求的uri
        String requestURI = req.getRequestURI();
        //根据用户请求的uri返回mvcMping
        HandlerMapping.MVCMping mvcMping = HandlerMapping.get(requestURI);
        //判断用户请求地址是否存在
        if(mvcMping == null){
            resp.sendError(404,"自定义MVC，映射地址不存在。uri="+requestURI);
            return;
        }
        Object obj = mvcMping.getObj();
        Method method = mvcMping.getMethod();

        Object result=null;
        //规定其方法必须返回String类型，
        try {
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //根据注解确定方法返回类型
        switch (mvcMping.getType()){
            case TEXT:
                resp.getWriter().write(String.valueOf(result));
                break;
            case VIEW:
                resp.sendRedirect(String.valueOf(result));
                break;
        }
    }
    }
